/**
 * File:   SimpleCleaner.java
 * Author: Gvennet
 */
package dht.cleaners;

import dht.network.Network;
import dht.node.DHTNodeModel;
import dht.node.DHTNodeRow;

import java.io.IOException;
import java.util.List;

/**
 * todo write javadoc
 */
public final class SimpleCleaner implements NodeModelCleaner, Runnable
{

	private DHTNodeModel nodeModel;

	private final Network network;

	public SimpleCleaner(Network network)
	{
		this.network = network;
	}

	@Override
	public void clean()
	{
		if (nodeModel != null)
		{
			List<DHTNodeRow> nodes = nodeModel.getNodes();
			if (nodes.size() > 0.75 * nodeModel.getMaxSize())
			{
				for (DHTNodeRow node : nodes)
				{
					try
					{
						network.sendPingRequest(node.getInetAddress(), node.getPort());
					}
					catch (IOException e)
					{
						throw new RuntimeException(e); //todo
					}
				}
			}
		}
	}

	@Override
	public void setNodeModel(DHTNodeModel nodeModel)
	{
		this.nodeModel = nodeModel;
	}

	@Override
	public void run()
	{
		clean();
	}
}
